package cn.gz.demo.ui.oss;

import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.alibaba.sdk.android.oss.ClientConfiguration;
import com.alibaba.sdk.android.oss.OSS;
import com.alibaba.sdk.android.oss.OSSClient;
import com.alibaba.sdk.android.oss.common.auth.OSSCredentialProvider;
import com.alibaba.sdk.android.oss.common.auth.OSSPlainTextAKSKCredentialProvider;

import java.io.File;
import java.io.IOException;
import java.lang.ref.WeakReference;

import cn.gz.demo.R;
import cn.gz.demo.ui.base.BaseActivity;
import cn.gz.demo.utils.LogUtil;

/**
 * Created by Liuyz on 2017/12/22.
 */
public class AliOssActivity extends BaseActivity {
    private static final int RESULT_LOAD_IMAGE = 1;
    private static final String endpoint = "http://oss-cn-shenzhen.aliyuncs.com";
    private static final String imgEndpoint = "http://img-cn-shenzhen.aliyuncs.com";
    private static final String callbackAddress = "http://oss-demo.aliyuncs.com:23450";
    private static final String bucket = "hctmt";
    private static final String accessKeyId = "LTAI4ncYUfnPZl2V";
    private static final String accessKeySecret = "jactVnZvAdu61ce10guF42nRjYnuRC";

    ImageView imageView;
    Button select;
    EditText edit_text;
    ProgressBar bar;
    Button upload;
    TextView textView;

    //负责所有的界面更新
    private UIDisplayer UIDisplayer;
    //OSS的上传下载
    private OssService ossService;
    private ImageService imageService;
    private String picturePath = "";
    private WeakReference<PauseableUploadTask> task;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_ali_oss);

        imageView = (ImageView) findViewById(R.id.imageView);
        select = (Button) findViewById(R.id.select);
        textView = (TextView) findViewById(R.id.output_info);
        edit_text = (EditText) findViewById(R.id.edit_text);
        bar = (ProgressBar) findViewById(R.id.bar);
        upload = (Button) findViewById(R.id.upload);

        UIDisplayer = new UIDisplayer(imageView, bar, textView, this);
        ossService = initOSS(endpoint, bucket);
        //设置上传的callback地址，目前暂时只支持putObject的回调
        ossService.setCallbackAddress(callbackAddress);

        //图片服务和OSS使用不同的endpoint，但是可以共用SDK，因此只需要初始化不同endpoint的OssService即可
        imageService = new ImageService(initOSS(imgEndpoint, bucket));


        select.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Intent i = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                startActivityForResult(i, RESULT_LOAD_IMAGE);
            }
        });
        upload.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                EditText editText = (EditText) findViewById(R.id.edit_text);
                String objectName = editText.getText().toString();
                ossService.asyncPutImage(objectName, picturePath, new UploadCallBack() {
                    @Override
                    public void onSuccess(String msg) {
                        LogUtil.showLog(".....onSuccess....");
                    }

                    @Override
                    public void onFail(String msg) {
                        LogUtil.showLog("....onFail.....");
                    }

                    @Override
                    public void onProgress(int pro) {
                        LogUtil.showLog("....onProgress....."+pro);
                    }
                });
            }
        });
    }

    //初始化一个OssService用来上传下载
    public OssService initOSS(String endpoint, String bucket) {
        //如果希望直接使用accessKey来访问的时候，可以直接使用OSSPlainTextAKSKCredentialProvider来鉴权。
        OSSCredentialProvider credentialProvider = new OSSPlainTextAKSKCredentialProvider(accessKeyId, accessKeySecret);

        ClientConfiguration conf = new ClientConfiguration();
        conf.setConnectionTimeout(15 * 1000); // 连接超时，默认15秒
        conf.setSocketTimeout(15 * 1000); // socket超时，默认15秒
        conf.setMaxConcurrentRequest(5); // 最大并发请求书，默认5个
        conf.setMaxErrorRetry(2); // 失败后最大重试次数，默认2次
        OSS oss = new OSSClient(getApplicationContext(), endpoint, credentialProvider, conf);
        return new OssService(oss, bucket);

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
            Uri selectedImage = data.getData();
            String[] filePathColumn = {MediaStore.Images.Media.DATA};
            Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
            cursor.moveToFirst();
            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            picturePath = cursor.getString(columnIndex);
            Log.d("PickPicture", picturePath);
            cursor.close();
            try {
                Bitmap bm = UIDisplayer.autoResizeFromLocalFile(picturePath);
                UIDisplayer.displayImage(bm);
                /*
                ImageView imageView = (ImageView) findViewById(R.id.imageView);
                imageView.setImageBitmap(bm);*/
                File file = new File(picturePath);
                UIDisplayer.displayInfo("文件: " + picturePath + "\n大小: " + String.valueOf(file.length()));
            } catch (IOException e) {
                e.printStackTrace();
                UIDisplayer.displayInfo(e.toString());
            }
        }
    }
}
